package design.simdi.code.final_paper.site.pages;

import org.apache.wicket.authentication.AuthenticatedWebSession;
import org.apache.wicket.feedback.FeedbackMessage;
import org.apache.wicket.feedback.IFeedbackMessageFilter;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.StatelessForm;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.EmptyPanel;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.util.value.ValueMap;

import design.simdi.code.final_paper.core.services.UserService;

/**
 * 
 * @author Marius Dumitriu - (May 24, 2010 - 1:17:46 AM)
 * 
 */
public class LoginPage extends BasePage {

	private PasswordTextField password;
	private TextField<String> username;
	@SpringBean
	private UserService userService;

	public LoginPage() {
		get("link.login").setVisible(false);
		get("link.register").setVisible(false);
		get("menu").replaceWith(new EmptyPanel("menu"));
		get(BasePage.ERRORS_PANEL).setVisible(false);
		add(new SignInForm("signInForm"));

	}

	public final class SignInForm extends StatelessForm<Void> {
		private static final long serialVersionUID = 1L;

		private final ValueMap properties = new ValueMap();

		public SignInForm(final String id) {
			super(id);

			add(username = new TextField<String>("username", new PropertyModel<String>(properties, "username")));
			add(password = new PasswordTextField("password", new PropertyModel<String>(properties, "password")));

			username.setType(String.class);
			password.setType(String.class);
			// username.setPersistent(true);

			add(new FeedbackPanel("error", new IFeedbackMessageFilter() {

				private static final long serialVersionUID = 1L;

				public boolean accept(FeedbackMessage message) {
					return message.getLevel() == FeedbackMessage.ERROR;
				}
			}));

		}

		/**
		 * @see org.apache.wicket.markup.html.form.Form#onSubmit()
		 */
		@Override
		public final void onSubmit() {
			if (signIn(getUsername(), getPassword())) {
				onSignInSucceeded();
			} else {
				onSignInFailed();
			}
		}
	}

	public String getPassword() {
		return password.getInput();
	}

	public String getUsername() {
		return username.getDefaultModelObjectAsString();
	}

	public boolean signIn(String username, String password) {
		return AuthenticatedWebSession.get().signIn(username, password);
	}

	protected void onSignInFailed() {

		error(getString("bad.credentials"));
	}

	protected void onSignInSucceeded() {

		if (!continueToOriginalDestination()) {
			setResponsePage(getApplication().getHomePage());
		}
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public UserService getUserService() {
		return userService;
	}

}
